package com.zlb.leyaoxiu2.sqlite;

import com.zlb.leyaoxiu2.sqlite.entity.ImChatType;
import com.zlb.leyaoxiu2.sqlite.entity.ImMessage;
import com.zlb.leyaoxiu2.sqlite.entity.SystemMessage;

import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;

/**
 * Created by Administrator on 2016/8/23.
 */
public class SystemMessageUtil {

    public static RealmResults<SystemMessage> getSystemMessageList(Realm realm, String userId) {
        RealmResults<SystemMessage> results = realm.where(SystemMessage.class).equalTo("userId", userId).findAllSorted("msgTime", Sort.DESCENDING);
        return results;
    }

    public static void insertOrUpdateSystemMessageByIm(Realm realm, boolean isBeginRealm, ImMessage msg, String nickName, String iconUrl) {
        if (isBeginRealm) {
            realm.beginTransaction();
        }
        //插入系统消息
        SystemMessage systemMessage = new SystemMessage();

        systemMessage.setUserId(msg.getUserId());
        systemMessage.setPeerId(msg.getPeerId());
        systemMessage.setNickName(nickName);
        systemMessage.setIconUrl(iconUrl);
        systemMessage.setLastMsgType(msg.getMsgType());

        systemMessage.setLastMsg(msg.getContent());
        systemMessage.setMsgTime(msg.getMsgTime());
        systemMessage.setSystemMsgType(ImChatType.SYSTEM_TYPE_IM);
        systemMessage.setMsgUnique(ImChatType.getSystemMsgUnique(msg.getUserId(), msg.getPeerId()));
        //取出每一条的未读消息
        systemMessage.setUnReadCount(ImMessageUtil.getUnReadCount(realm, msg.getUserId(), msg.getPeerId()));
        systemMessage.setUserLevel(msg.getUserLevel());

        realm.insertOrUpdate(systemMessage);

        if (isBeginRealm) {
            realm.commitTransaction();
        }
    }
}
